import * as xlsx from "node-xlsx";
import { EnumExportPlatform, EnumExportType } from "./Enum";
import { Utils } from "./utils/Utils";
const excelRootpath = './excel/';
const exportRootpath = './build/';
const exportInterfacePath = './build/IGame.ts';
export default class Main {
    /**
     * 解析xlsx中的每一个sheet为json数据
     * @param tables 
     */
    pasreTablesToJson(tables: { name: string; data: unknown[][]; }[], from?: string) {
        let tableJson = {};
        tables.forEach((sheet) => {
            let sheetJson: any[];
            if (from) {
                sheetJson = this.parseTaleDataToJson(sheet.data, `${from}>${sheet.name}`);
            } else {
                sheetJson = this.parseTaleDataToJson(sheet.data);
            }
            tableJson[sheet.name] = sheetJson;
        })
        return tableJson;
    }
    async getLangJson() {
        return await this.getJsonByTablePath(`${excelRootpath}lang.xlsx`);
    }
    /**
     * 解析xlsx中的每一个sheet为interface接口
     * @param tables 
     */
    pasreTablesToInterface(tables: { name: string; data: unknown[][]; }[]) {
        let allInterface = '';
        let IGameConfig = '';
        tables.forEach((sheet) => {
            let interface_obj = this.parseTaleDataToInterface(sheet.data);
            let interface_name = `I${sheet.name[0].toUpperCase()}${sheet.name.substr(1)}`;
            let result = JSON.stringify(interface_obj).replace(/\"/g, "");
            let config_temp = `${sheet.name}: ${interface_name}[] = [];\n`
            let interface_temp = `
            export interface ${interface_name}${result}
            `;
            allInterface += interface_temp;
            IGameConfig += config_temp;
        })
        return { allInterface: allInterface, IGameConfig: IGameConfig };
    }
    /**
     * 将xlsx中表格的数据转换为json对象
     * @param data 
     * @returns 
     */
    parseTaleDataToJson(data: any[][], from?: string) {
        let titles = data[0];
        let exportPlatforms = data[1];
        let exportType = data[2];
        let jsons = [];
        if (!exportPlatforms.length) {
            return [];
        }
        data = data.filter((line) => {
            return line.length
        })
        for (let i = 3; i < data.length; i++) {
            let line_data = data[i];
            let line_obj = {};
            for (let j = 0; j < titles.length; j++) {
                if (!line_data[0]) {
                    continue;
                }
                let title = titles[j];
                let platform = exportPlatforms[j];
                let type = exportType[j];
                let grid_data = line_data[j];
                if (platform == EnumExportPlatform.all || platform == EnumExportPlatform.client || platform == EnumExportPlatform.server) {
                    let value = this.conversionType(grid_data, type);
                    line_obj[title] = value;
                    if (from && Utils.isChinese(grid_data)) {
                        let froms = `${from}>${title}>${titles[0]}>${line_data[0]}`;
                        line_obj[froms] = grid_data;
                    }
                }
            }
            jsons.push(line_obj);
        }
        return jsons;
    }
    /**
     * 将xlsx中表格的数据转换为interface
     * @param data 
     * @returns 
     */
    parseTaleDataToInterface(data: any[][]) {
        let titles = data[0];
        let exportPlatforms = data[1];
        let exportType = data[2];
        let interface_obj = {};
        for (let i = 0; i < titles.length; i++) {
            let title = titles[i];
            let platform = exportPlatforms[i];
            let type = exportType[i];
            if (platform == EnumExportPlatform.all || platform == EnumExportPlatform.client || platform == EnumExportPlatform.server) {
                interface_obj[title] = type;
            }
        }
        return interface_obj;
    }
    /**
     * 获取指定xlsx生成的json
     * @param path 
     */
    async getJsonByTablePath(excelPath: string, from?: string) {

        let buffer = await Utils.readFile(excelPath);
        let sheets = xlsx.parse(buffer);
        let jsons = this.pasreTablesToJson(sheets, from);
        return jsons;
    }
    async exportJson(rootPath: string, exportInterface: boolean = true) {
        let paths = await Utils.readdir(rootPath);
        await Utils.unlinkDir(exportRootpath);
        let allInterface = '';
        let IGameConfigStartTemp = `export class IGameConfig {\n`

        for await (const path of paths) {
            let fileName = path.split('.')[0];
            let excelPath = `${excelRootpath}${path}`;
            if (Utils.validFolder(excelPath)) {
                let buffer = await Utils.readFile(excelPath);
                let sheets = xlsx.parse(buffer);
                let jsons = await this.getJsonByTablePath(excelPath);
                let interfaces = this.pasreTablesToInterface(sheets);
                allInterface += interfaces.allInterface;
                IGameConfigStartTemp += interfaces.IGameConfig;
                const jsonOutputPath = `${exportRootpath}${fileName}.json`;
                await Utils.writeFile(jsonOutputPath, JSON.stringify(jsons, null, "\t"));
            }
        }
        if (exportInterface) {
            IGameConfigStartTemp += '}';
            allInterface += IGameConfigStartTemp;
            await Utils.writeFile(exportInterfacePath, allInterface);
        }
    }


    /**
     * 类型转换
     */
    conversionType(data: string, type: EnumExportType) {
        let result = null;
        switch (type) {
            case EnumExportType.number:
                result = data ? +data : 0;
                break;
            case EnumExportType.string:
                result = data ? `${data}` : '';
                break;
            case EnumExportType.stringArr:
                result = data ? this.strToStingArr(data) : [];
                break;
            case EnumExportType.numberArr:
                result = data ? this.strToNumberArr(data) : [];
                break;
            default:
                break;
        }
        return result;
    }
    strToStingArr(data: string) {
        if (!data) {
            return null;
        }
        return `${data}`.split(',');
    }
    strToNumberArr(data: string) {
        if (!data) {
            return null;
        }
        let arr = `${data}`.split(',');
        let numberArr = [];
        arr.map((item) => {
            numberArr.push(+item);
        })
        return numberArr;
    }


}



